package com.meiyuetao.yox.web.action;

import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.customer.entity.CustomerProfile;
import com.meiyuetao.myt.customer.service.CustomerProfileService;
import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.service.BoxOrderService;
import com.meiyuetao.myt.vip.entity.VipCustomerProfile;
import com.meiyuetao.myt.vip.entity.VipWxQrcode;
import com.meiyuetao.myt.vip.service.VipCustomerProfileService;
import com.meiyuetao.myt.vip.service.VipLevelService;
import com.meiyuetao.myt.vip.service.VipWxQrcodeService;
import com.meiyuetao.yox.entity.YxCustomerBindInfo;
import com.meiyuetao.yox.service.YxCustomerBindInfoService;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.view.OperationResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;

import java.io.File;
import java.util.List;

@MetaData("优享一百用户微信绑定管理")
public class YxCustomerBindInfoController extends MytBaseController<YxCustomerBindInfo, Long> {

    @Autowired
    private YxCustomerBindInfoService yxCustomerBindInfoService;

    @Autowired
    private VipWxQrcodeService vipWxQrcodeService;

    @Autowired
    private CustomerProfileService customerProfileService;

    @Autowired
    private VipCustomerProfileService vipCustomerProfileService;

    @Autowired
    private VipLevelService vipLevelService;

    @Autowired
    private BoxOrderService boxOrderService;

    private File customerExcel;

    @Override
    protected BaseService<YxCustomerBindInfo, Long> getEntityService() {
        return yxCustomerBindInfoService;
    }

    @Override
    protected void checkEntityAclPermission(YxCustomerBindInfo entity) {
    }

    @Override
    @MetaData("创建")
    public HttpHeaders doCreate() {
        return super.doCreate();
    }

    @Override
    @MetaData("更新")
    public HttpHeaders doUpdate() {
        return super.doUpdate();
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        if (bindingEntity.isNotNew()) {
            VipCustomerProfile vipCustomerProfile = bindingEntity.getCustomerProfile().getVipCustomerProfile();
            vipCustomerProfile.setCustomerProfile(customerProfileService.findOne(vipCustomerProfile.getId()));
            vipCustomerProfileService.save(vipCustomerProfile);
            return super.doSave();
        }
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.forceAnd(new PropertyFilter(PropertyFilter.MatchType.EQ, "mobile", bindingEntity.getMobile()));
        groupPropertyFilter.forceAnd(new PropertyFilter(PropertyFilter.MatchType.EQ, "customerProfile.customerFrom", "ZHONGZI"));
        List<YxCustomerBindInfo> list = yxCustomerBindInfoService.findByFilters(groupPropertyFilter);
        if (CollectionUtils.isNotEmpty(list)) {
            setModel(OperationResult.buildFailureResult("该手机号已经存在"));
            return buildDefaultHttpHeaders();
        }
        bindingEntity.setBindStatus(YxCustomerBindInfo.BindStatusEnum.NO);
        CustomerProfile customer = new CustomerProfile();
        VipCustomerProfile vipCustomerProfile = new VipCustomerProfile();
        customer.setTrueName(bindingEntity.getTrueName());
        customer.setMobilePhone(bindingEntity.getMobile());
        customer.setCustomerFrom("ZHONGZI");
        customer.setCustomerNameType("8");//iyou通行证
        customerProfileService.save(customer);
        vipCustomerProfile.setCustomerProfile(customer);
        // 生成皇冠用户
        vipCustomerProfile.setVipLevel(vipLevelService.findOne(Long.valueOf(5)));
        vipCustomerProfileService.save(vipCustomerProfile);
        // 关联微信二维码
        GroupPropertyFilter qrcodeGPF = GroupPropertyFilter.buildDefaultAndGroupFilter();
        qrcodeGPF.forceAnd(new PropertyFilter(PropertyFilter.MatchType.NU, "customerProfile", true));
        List<VipWxQrcode> listVwq = vipWxQrcodeService.findByFilters(qrcodeGPF, new Sort(Sort.Direction.DESC, "createdDate"), 1);
        VipWxQrcode vipWxQrcode = listVwq.get(0);
        vipWxQrcode.setCustomerProfile(customer);
        vipWxQrcode.setVipCustomerProfile(vipCustomerProfile);
        vipWxQrcodeService.save(vipWxQrcode);
        bindingEntity.setCustomerProfile(customer);
        return super.doSave();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @MetaData("升级")
    public HttpHeaders merge() {
        String mergeErr = "";
        if (StringUtils.isNotBlank(getParameter("ids"))) {
            Long[] ids = this.getSelectSids();
            List<YxCustomerBindInfo> list = yxCustomerBindInfoService.findAll(ids);
            for (YxCustomerBindInfo bindInfo : list) {
                CustomerProfile ptc = bindInfo.getCustomerProfile();
                GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                groupPropertyFilter.forceAnd(new PropertyFilter(PropertyFilter.MatchType.EQ, "mobile", bindInfo.getMobile()));
                groupPropertyFilter.forceAnd(new PropertyFilter(PropertyFilter.MatchType.EQ, "bindStatus", YxCustomerBindInfo.BindStatusEnum.NO));
                groupPropertyFilter.forceAnd(new PropertyFilter(PropertyFilter.MatchType.EQ, "customerProfile.customerFrom", "ZHONGZI"));
                List<YxCustomerBindInfo> zzList = yxCustomerBindInfoService.findByFilters(groupPropertyFilter);
                if (!CollectionUtils.isEmpty(zzList)) {
                    YxCustomerBindInfo yinceBind = zzList.get(0);
                    //皇冠用户的微信uid置为和普通用户一样
                    CustomerProfile huangguan = yinceBind.getCustomerProfile();
                    huangguan.setWeixinId(ptc.getWeixinId());
                    huangguan.setOpenid(ptc.getOpenid());
                    huangguan.setHeadPhoto(ptc.getHeadPhoto());
                    huangguan.setCustomerName(ptc.getCustomerName());
                    ptc.setWeixinId("-" + ptc.getWeixinId());
                    ptc.setOpenid("-" + ptc.getOpenid());
                    customerProfileService.save(ptc);
                    bindInfo.setCustomerProfile(huangguan);
                    bindInfo.setBindStatus(YxCustomerBindInfo.BindStatusEnum.OK);
                    bindInfo.setTrueName(yinceBind.getTrueName());
                    bindInfo.setHospital(yinceBind.getHospital());
                    bindInfo.setMemo(yinceBind.getMemo());
                    yxCustomerBindInfoService.save(bindInfo);
                    // 判断普通用户是否有订单 如果有订单 则 将订单重新赋给 皇冠用户
                    GroupPropertyFilter boxgp = GroupPropertyFilter.buildDefaultAndGroupFilter();
                    boxgp.forceAnd(new PropertyFilter(PropertyFilter.MatchType.EQ, "customerProfile", ptc));
                    List<BoxOrder> orders = boxOrderService.findByFilters(boxgp);
                    if (CollectionUtils.isNotEmpty(orders)) {
                        for (BoxOrder boxOrder : orders) {
                            boxOrder.setCustomerProfile(huangguan);
                            boxOrderService.save(boxOrder);
                        }
                    }
                } else {
                    mergeErr += "手机号： " + bindInfo.getMobile() + "升级失败\r\n";
                }
            }
        }
        if (StringUtils.isNotEmpty(mergeErr)) {
            setModel(OperationResult.buildFailureResult(mergeErr));
        } else {
            setModel(OperationResult.buildSuccessResult("升级成功"));
        }

        return buildDefaultHttpHeaders();
    }

    @MetaData("生成准皇冠用户")
    public HttpHeaders createCustomer() {
        if (customerExcel == null) {
            setModel(OperationResult.buildFailureResult("请选择上传文件"));
            return buildDefaultHttpHeaders();
        }
        String createIndo = "";
        try {
            createIndo = yxCustomerBindInfoService.createCustomer(customerExcel);
        } catch (Exception e) {
            setModel(OperationResult.buildFailureResult("excel解析错误"));
            return buildDefaultHttpHeaders();
        }
        if (StringUtils.isNotBlank(createIndo)) {
            setModel(OperationResult.buildFailureResult(createIndo));
        } else {
            setModel(OperationResult.buildSuccessResult("成功生成"));
        }
        return buildDefaultHttpHeaders();
    }

    @MetaData("解绑")
    public HttpHeaders unbunde() {
        super.doDelete();
        setModel(OperationResult.buildSuccessResult("解绑成功"));
        return buildDefaultHttpHeaders();
    }

    @MetaData("解绑并降级")
    public HttpHeaders rollback() {
        String rollbackErr = "";
        if (StringUtils.isNotBlank(getParameter("ids"))) {
            Long[] ids = this.getSelectSids();
            List<YxCustomerBindInfo> list = yxCustomerBindInfoService.findAll(ids);
            for (YxCustomerBindInfo bindInfo : list) {
                CustomerProfile huangGuanBind = bindInfo.getCustomerProfile();
                String weixinUnoin = huangGuanBind.getWeixinId();
                String weixinOpen = huangGuanBind.getOpenid();
                if (StringUtils.isEmpty(weixinUnoin)) {
                    rollbackErr += "用户：" + bindInfo.getTrueName() + "的微信id不存在\r\n";
                    continue;
                }
                CustomerProfile beforeBind = customerProfileService.findByProperty("weixinId", "-" + weixinUnoin);
                if (beforeBind == null) {
                    rollbackErr += "用户：" + bindInfo.getTrueName() + "的升级前的用户不存在\r\n";
                    continue;
                }
                // 解绑将原先普通用户的微信恢复
                beforeBind.setWeixinId(weixinUnoin);
                beforeBind.setOpenid(weixinOpen);
                // 解绑将皇冠用户的微信置为不可用
                huangGuanBind.setWeixinId("-" + weixinUnoin);
                huangGuanBind.setOpenid("-" + weixinOpen);
                customerProfileService.save(beforeBind);
                customerProfileService.save(huangGuanBind);
                yxCustomerBindInfoService.delete(bindInfo);
            }
        }
        if (StringUtils.isNotEmpty(rollbackErr)) {
            setModel(OperationResult.buildFailureResult(rollbackErr));
        } else {
            setModel(OperationResult.buildSuccessResult("解绑降级成功"));
        }
        return buildDefaultHttpHeaders();
    }

    @MetaData("获取二维码")
    public HttpHeaders getQrcode() {
        String cusomerProfile = getParameter("customerProfile");
        CustomerProfile cp = customerProfileService.findOne(Long.valueOf(cusomerProfile));
        VipWxQrcode vipWxQrcode = vipWxQrcodeService.findByProperty("customerProfile", cp);
        if (vipWxQrcode == null) {
            vipWxQrcode = vipWxQrcodeService.findByProperty("vipCustomerProfile", cp.getVipCustomerProfile());
        }
        setModel(vipWxQrcode);
        return buildDefaultHttpHeaders();
    }

    @MetaData("获取上线")
    public HttpHeaders getUpstream() {
        String cusomerProfile = getParameter("customerProfile");
        CustomerProfile cp = customerProfileService.findOne(Long.valueOf(cusomerProfile));
        setModel(cp.getVipCustomerProfile().getUpstream());
        return buildDefaultHttpHeaders();
    }

    public File getCustomerExcel() {
        return customerExcel;
    }

    public void setCustomerExcel(File customerExcel) {
        this.customerExcel = customerExcel;
    }
}